package com.xf.common.security.starter.handler;

import com.xf.common.core.domain.DmpResult;
import com.xf.common.core.utils.FebsUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * 表单认证的异常处理
 * 返回json 授权码模式返回重定向url由前端跳转  其他模式只返回报错json
 * 注意源码可能会从header 获取别的实现.导致覆盖本配置.返回默认json.关闭basic认证
 * https://blog.csdn.net/hou_ge/article/details/120435303
 *
 * @author xufeng
 */
@Slf4j
@Component
public class LoginFormAuthExceptionEntryPoint implements AuthenticationEntryPoint {

    @Override
    @SneakyThrows(Exception.class)
    public void commence(HttpServletRequest request, HttpServletResponse response,
                         AuthenticationException authException) {
        String requestUri = request.getRequestURI();
        int status = HttpServletResponse.SC_UNAUTHORIZED;
        String message = "访问令牌不合法";
        log.error("客户端访问{}请求失败: {}", requestUri, message);
        log.debug(authException.getMessage());

        Map<String, String[]> paramMap = request.getParameterMap();
        StringBuilder param = new StringBuilder();
        paramMap.forEach((k, v) -> {
            param.append("&").append(k).append("=").append(v[0]);
        });
        //param.deleteCharAt(0); 去掉参数前的& 非空异常.先注释
        String isRedirectValue = request.getParameter("isRedirect");
        //未登录 用户带上重定向请求跳转到前端
        if (!StringUtils.isEmpty(isRedirectValue) && Boolean.parseBoolean(isRedirectValue)) {
            response.sendRedirect("http://localhost:9527/#/login/1?" + param);
            return;
        }
        //返回认证地址给前端
        String authUrl = "http://localhost:8301/auth/oauth/authorize?" + param + "&isRedirect=true";

        FebsUtil.makeJsonResponse(response, status, new DmpResult(authUrl, "800", message));
    }

}

